package jmine.tec.web.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmine.tec.utils.io.IOUtils;

/**
 * Servlet que delega para o servidor de aplicacoes
 * 
 * @author takeshi
 */
public class WebContextResourceServlet extends HttpServlet {

    private static final String REDIRECT_PARAMETER_NAME = "rootRequestRedirect";

    private String redirectRoot = "/index.html";

    /**
     * {@inheritDoc}
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        if (config.getInitParameter(REDIRECT_PARAMETER_NAME) != null) {
            this.redirectRoot = config.getInitParameter(REDIRECT_PARAMETER_NAME);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            path += pathInfo;
        }
        if ("/".equals(path) || "".equals(path)) {
            path = this.redirectRoot;
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        InputStream stream = getServletContext().getResourceAsStream(path);
        String mimeType = getServletContext().getMimeType(path);
        if (stream == null) {
            stream = getServletContext().getResourceAsStream(this.redirectRoot);
        }
        if (mimeType != null) {
            resp.setContentType(mimeType);
        }
        IOUtils.copyFully(stream, resp.getOutputStream());
    }

}
